package com.vcredit.creditcat.service;

import com.vcredit.creditcat.model.CardCondition;
import com.vcredit.creditcat.persistence.base.CardConditionMapper;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/*
 * @author zhangxingong
 * @version 1.0
 * @since 1.0
*/
@Service
public class CardConditionService {

  @Autowired
  private CardConditionMapper cardConditionMapper;

  @Cacheable(value = "cardCondition",key = "'condition:cardCondition'")
  public List<CardCondition> find(CardCondition cardCondition) {
    return cardConditionMapper.find(cardCondition);
  }

  @Cacheable(value = "cardCondition",key = "'condition:cardCondition'")
  public CardCondition findById(Long cardConditionId) {
    return cardConditionMapper.findById(cardConditionId);
  }

  @Cacheable(value = "cardCondition",key = "'condition:cardConditions'")
  public List<CardCondition> findAll() {
    return cardConditionMapper.findAll();
  }

  @Cacheable(value = "cardCondition",key = "'condition:cardCondition_'+#cardId + '_' + #type")
  public List<CardCondition> findByIdAndType(Long cardId, Integer type) {
    List<CardCondition> conditionList = this.findAll();
    Iterator<CardCondition> iterator = conditionList.iterator();
    while (iterator.hasNext()) {
      CardCondition condition = iterator.next();
      if (ObjectUtils.notEqual(cardId, condition.getCardId()) || condition.getConditionType()!=type) {
        iterator.remove();
      }
    }
    return conditionList;
  }

  @CacheEvict(value = "cardCondition",key = "'condition:cardConditio*'")
  public void insert(CardCondition cardCondition) {
    cardConditionMapper.insert(cardCondition);
  }

  @CacheEvict(value = "cardCondition",key = "'condition:cardConditio*'")
  public void update(CardCondition cardCondition) {
    cardConditionMapper.update(cardCondition);
  }

  private void delete(Long id) {
    cardConditionMapper.delete(id);
  }

  @CacheEvict(value = "cardCondition",key = "'condition:cardCondition*'",beforeInvocation=true)
  public void clearcardConditionCache() {
    System.out.println("cardCondition");
  }
}
